/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI_SIFACT;

import AccesoDatosAvanzado.AD_Clientes;
import AccesoDatosAvanzado.AD_Empleado_Users;
import AccesoDatosAvanzado.AD_Factura;
import AccesoDatosAvanzado.AD_Factura_Detalle;
import AccesoDatosAvanzado.AD_Producto;
import AccesoDatosSimple.cFactura;
import AccesoDatosSimple.cFactura_Detalle;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.table.DefaultTableModel;

import sifact.conexion.cConexion;

/**
 *
 * @author Cyber Huevadictos
 */
public class Frm_Factura extends javax.swing.JDialog {

    Date fechaActual = new Date();
    String ahora = "00/00/0000";
    //FORMATENADO LA FECHA 
    SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");
    //PARA ESCUCHAR EL EVENTO DE LA TECLA ENTER EN EL JTABLE
    private static final String solve = "Solve";
    KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
    KeyStroke supr = KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0);
    //para crear filas dinamicamente en el jTable
    Object[] fila = new Object[2];
    //valor del IVA actual
    private static final double IVA = 0.12;
    private static final String FORMATO4 = "####0.000";
    private static final String FORMATO2 = "####0.00";
    private String txtnulos = "Los Campos Vacios son:\n";
    char band = '0';

    /**
     * Creates new form Frm_Factura
     */
    public Frm_Factura(String findobjeto, int caso) {
        String idcliente = "";
        String idempleado = "";
        try {
            initComponents();
            switch (caso) {
                case 1://anular factura
                    //lleno la factura con los datos consultados
                    String[] tupla = new String[10];
                    tupla = AD_Factura.BuscarFacturaCodigo(findobjeto);
                    jTextFieldNumFactura.setText(tupla[0]);
                    //lleno el detalle de la factura
                    ArrayList DetalleFactura = AD_Factura_Detalle.BuscarFacturaDetalleCodigo(tupla[0]);
                    DefaultTableModel modelo;// = new DefaultTableModel();
                    modelo = (DefaultTableModel) jTable1.getModel();
                    modelo.removeRow(0);
                    FilasColumnas();
                    DecimalFormatSymbols simbolos = new DecimalFormatSymbols();
                    simbolos.setDecimalSeparator('.');
                    for (int i = 0; i < DetalleFactura.size(); i++) {
                        //llenar fila a fila el detalle
                        String[] tupladetalle = new String[10];
                        String[] tuplaproducto = new String[10];
                        String[] aux = new String[6];
                        tupladetalle = (String[]) DetalleFactura.get(i);
                        tuplaproducto = AD_Producto.BuscarCodigo(tupladetalle[1]);
                        aux[0] = tupladetalle[1];//numIDProducto
                        aux[1] = tuplaproducto[1];//Nombre del Producto
                        aux[2] = tuplaproducto[2];//UNidades
                        //formateo la salida a 2 decimales y punto                        
                        DecimalFormat df = new DecimalFormat(FORMATO2, simbolos);
                        aux[3] = df.format(Double.parseDouble(tupladetalle[3]));//Precio Unitario
                        aux[4] = tupladetalle[2];//Cantidad
                        aux[5] = Double.toString(Double.parseDouble(tupladetalle[2]) * Double.parseDouble(tupladetalle[3]));//Total
                        modelo.addRow(aux);
                    }
                    jTable1.setModel(modelo);

                    //almaceno datos para no perderlos y seguir con las otras busquedas
                    idcliente = tupla[1];
                    idempleado = tupla[2];
                    jComboBoxFormPago.setSelectedItem(tupla[2]);
                    jComboBoxFormPago.setEnabled(false);
                    DecimalFormat df = new DecimalFormat(FORMATO2, simbolos);
                    jTextFieldSubTotal.setText(df.format(Double.parseDouble(tupla[4])));
                    jTextFieldIva12.setText(df.format(Double.parseDouble(tupla[4]) * IVA));
                    jLabelTotal.setText(df.format(Double.parseDouble(jTextFieldSubTotal.getText()) + Double.parseDouble(jTextFieldIva12.getText())));
                    //jComboBoxEstado.setSelectedItem(tupla[5]);  
                    jComboBoxEstado.setSelectedIndex(1);
                    jComboBoxEstado.setEnabled(false);
                    jLabelFecha.setText(tupla[6]);

                    //id cliente
                    tupla = AD_Clientes.BuscarIDCliente(idcliente);
                    jTextFieldCedula.setText(tupla[1]);
                    jTextFieldNombres.setText(tupla[2] + " " + tupla[3]);
                    jTextAreaDireccion.setText(tupla[4]);
                    jTextFieldTlfno.setText(tupla[5]);

                    //id empleado
                    tupla = AD_Empleado_Users.BuscarNumID(idempleado);
                    jTextFieldEmpleado.setText(tupla[1]);
                    band = '1';
                    break;
                case 2://modificar estado
                    break;
                default:
                    //OBTENIENDO LA FECHA ACTUAL DEL SISTEMA
                    ahora = formato.format(fechaActual);
                    jLabelFecha.setText(ahora);
                    FilasColumnas();
                    //reaccione a la tecla <Enter>
                    jTable1.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(enter, solve);
                    jTable1.getActionMap().put(solve, new EnterAction());
                    //reaccione a la tecla <Supr>
                    jTable1.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(supr, rootPane);
                    jTable1.getActionMap().put(rootPane, new SuprAction());
                    break;
            }
        } catch (Exception ex) {
            Logger.getLogger(Frm_Factura.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void FilasColumnas() {
        //para modificar los tamaños de las columnas del jTable
        jTable1.getColumnModel().getColumn(0).setPreferredWidth(10);
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(400);
        jTable1.getColumnModel().getColumn(2).setPreferredWidth(10);
        jTable1.getColumnModel().getColumn(3).setPreferredWidth(15);
        jTable1.getColumnModel().getColumn(4).setPreferredWidth(10);
        jTable1.getColumnModel().getColumn(5).setPreferredWidth(10);
        //PARA MODIFICAR LOS TAMAÑOS DE LAS FILAS
        jTable1.setRowHeight(25);
        jTable1.setCellSelectionEnabled(true);
    }
    //reaccione a la tecla <Supr>

    private class SuprAction extends AbstractAction {

        @Override
        public void actionPerformed(ActionEvent s) {//la accion que debe hacer
            ((DefaultTableModel) jTable1.getModel()).removeRow(jTable1.getSelectedRow());
            Calculos();
            if (jTable1.getRowCount() == 0) {
                fila[0] = "";//creo la fila
                ((DefaultTableModel) jTable1.getModel()).addRow(fila);
            }
        }
    }
//LA FUNCION MAESTRA QUE DA VIDA AL JTABLE
    //reaccione a la tecla <Enter>

    private class EnterAction extends AbstractAction {

        @Override
        public void actionPerformed(ActionEvent e) {
            //la celda sea editable y accesible
            jTable1.editCellAt(jTable1.getSelectedRow(), jTable1.getSelectedColumn());
            jTable1.getCellSelectionEnabled();
            //verifico que la celda no este vacia
            if (jTable1.getValueAt(jTable1.getSelectedRow(), jTable1.getSelectedColumn()) == null || jTable1.getValueAt(jTable1.getSelectedRow(), jTable1.getSelectedColumn()).equals("")) {
                JOptionPane.showMessageDialog(null, "LA CELDA NO PUEDE ESTAR VACIA", "ERROR", JOptionPane.ERROR_MESSAGE);
            } else {
                //un query para buscar el producto basandonos en su codigo
                String[] tupla = new String[10];
                try {
                    tupla = AD_Producto.BuscarCodigo(jTable1.getValueAt(jTable1.getSelectedRow(), 0).toString());
                    //reviso si existe o no algun dato almacenado en el vector string
                    if (tupla[0] == null) {
                        JOptionPane.showMessageDialog(null, "NO EXISTE EL PRODUCTO", "ERROR", JOptionPane.ERROR_MESSAGE);
                    } else {
                        jTable1.setValueAt(tupla[0], jTable1.getSelectedRow(), 0);
                        jTable1.setValueAt(tupla[1], jTable1.getSelectedRow(), 1);
                        jTable1.setValueAt(tupla[2], jTable1.getSelectedRow(), 2);

                        //formtateo la salida a 4 decimales y punto
                        DecimalFormatSymbols simbolos = new DecimalFormatSymbols();
                        simbolos.setDecimalSeparator('.');
                        DecimalFormat df = new DecimalFormat(FORMATO4, simbolos);

                        //formateo la salida del precio unitario para la venta
                        jTable1.setValueAt(df.format(Double.parseDouble(tupla[4])), jTable1.getSelectedRow(), 3);

                        //determino si estoy en la columna 0 y me paso a la columna 4
                        if (jTable1.getSelectedColumn() == 0) {
                            jTable1.setValueAt("", jTable1.getSelectedRow(), 4);
                            jTable1.changeSelection(jTable1.getSelectedRow(), 4, false, false);
                            jTable1.editCellAt(jTable1.getSelectedRow(), 4);
                            jTable1.requestFocus();
                        } else {//paso a la siguiente fila
                            if (jTable1.getSelectedColumn() == 4) {
                                fila[0] = "";//creo la fila
                                ((DefaultTableModel) jTable1.getModel()).addRow(fila);
//                        jTable1.editCellAt(jTable1.getSelectedRow()+1, 0);                       

                                //Calcular el total de cada producto
                                String valor = (String) jTable1.getValueAt(jTable1.getSelectedRow(), 3);
                                String cantidad = (String) jTable1.getValueAt(jTable1.getSelectedRow(), 4);
                                //formateo a 2 decimales                                
                                DecimalFormat dff = new DecimalFormat(FORMATO2, simbolos);
                                jTable1.setValueAt(dff.format(Double.parseDouble(valor) * Double.parseDouble(cantidad)), jTable1.getSelectedRow(), 5);
                                //funcion para calcular el valor de la factura
                                Calculos();
                                jTable1.getCellSelectionEnabled();
                                jTable1.setValueAt("", jTable1.getSelectedRow() + 1, 0);
                                jTable1.changeSelection(jTable1.getSelectedRow() + 1, 0, false, false);
                                jTable1.editCellAt(jTable1.getSelectedRow() + 1, 0);
                                jTable1.requestFocus();
                            }
                        }
                    }
                } catch (Exception ex) {
                }//terminar el query
            }
        }
    }
//funcion que me permite verificar los campos nulos del formulario

    private boolean CamposNulos() {
        boolean band = false;

        if (jTextFieldCedula.getText().trim().equals("")) {
            txtnulos = txtnulos + "CEDULA\n";
            band = true;
        }
        if (jTextFieldNumFactura.getText().trim().equals("")) {
            txtnulos = txtnulos + "NUMERO DE FACTURA\n";
            band = true;
        }
        return band;
    }

    public void Calculos() {
        //para hacer los calculos de los items de la factura        
        double iva0 = 0.0;
        double sumatoria = 0.0;

        for (int i = 0; i < (jTable1.getRowCount() - 1); i++) {
            sumatoria += Double.parseDouble(jTable1.getValueAt(i, 5).toString());
        }
        double iva12 = sumatoria * IVA;
        double total = sumatoria + iva12;
        //formtateo la salida a 2 decimales y punto
        DecimalFormatSymbols simbolos = new DecimalFormatSymbols();
        simbolos.setDecimalSeparator('.');
        DecimalFormat df = new DecimalFormat(FORMATO2, simbolos);
        //coloco los resultados en sus respectivo jLabel y jTextFields
        jTextFieldSubTotal.setText(df.format(sumatoria));
        jTextFieldIva12.setText(df.format(iva12));
        jLabelTotal.setText(df.format(total));
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanelCliente = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jTextFieldCedula = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jTextFieldNombres = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextAreaDireccion = new javax.swing.JTextArea();
        jTextFieldTlfno = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jPanelFactura = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        jTextFieldNumFactura = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jComboBoxFormPago = new javax.swing.JComboBox();
        jLabel8 = new javax.swing.JLabel();
        jComboBoxEstado = new javax.swing.JComboBox();
        jLabel9 = new javax.swing.JLabel();
        jTextFieldEmpleado = new javax.swing.JTextField();
        jLabelFecha = new javax.swing.JLabel();
        jPanelDetalleFactura = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jTextFieldSubTotal = new javax.swing.JTextField();
        jTextFieldIva0 = new javax.swing.JTextField();
        jTextFieldIva12 = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        jLabel12 = new javax.swing.JLabel();
        jLabelTotal = new javax.swing.JLabel();
        jLabel14 = new javax.swing.JLabel();
        jPanelBotones = new javax.swing.JPanel();
        jButtonAceptar = new javax.swing.JButton();
        jButtonCancelar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("FACTURA");

        jPanelCliente.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel1.setText("CEDULA:");

        jTextFieldCedula.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jTextFieldCedula.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jTextFieldCedulaKeyTyped(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel2.setText("NOMBRES:");

        jTextFieldNombres.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jTextFieldNombres.setEnabled(false);

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel3.setText("DIRECCION:");

        jScrollPane1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        jTextAreaDireccion.setColumns(20);
        jTextAreaDireccion.setRows(5);
        jTextAreaDireccion.setEnabled(false);
        jTextAreaDireccion.setOpaque(false);
        jScrollPane1.setViewportView(jTextAreaDireccion);

        jTextFieldTlfno.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jTextFieldTlfno.setEnabled(false);

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel4.setText("TELEFONO:");

        javax.swing.GroupLayout jPanelClienteLayout = new javax.swing.GroupLayout(jPanelCliente);
        jPanelCliente.setLayout(jPanelClienteLayout);
        jPanelClienteLayout.setHorizontalGroup(
            jPanelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelClienteLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanelClienteLayout.createSequentialGroup()
                        .addGroup(jPanelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanelClienteLayout.createSequentialGroup()
                                .addGroup(jPanelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel4))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGroup(jPanelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jTextFieldTlfno, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 343, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(jPanelClienteLayout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jTextFieldNombres, javax.swing.GroupLayout.PREFERRED_SIZE, 345, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addContainerGap())
                    .addGroup(jPanelClienteLayout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jTextFieldCedula, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(237, 237, 237))))
        );
        jPanelClienteLayout.setVerticalGroup(
            jPanelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelClienteLayout.createSequentialGroup()
                .addGap(6, 6, 6)
                .addGroup(jPanelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextFieldCedula, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGroup(jPanelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelClienteLayout.createSequentialGroup()
                        .addGap(35, 35, 35)
                        .addComponent(jLabel3)
                        .addGap(50, 50, 50)
                        .addComponent(jLabel4)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelClienteLayout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(jPanelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTextFieldNombres, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextFieldTlfno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(23, 23, 23))))
        );

        jPanelFactura.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel5.setText("NUMERO FACTURA:");

        jTextFieldNumFactura.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jTextFieldNumFactura.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jTextFieldNumFacturaKeyTyped(evt);
            }
        });

        jLabel6.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel6.setText("FECHA:");

        jLabel7.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel7.setText("FORMA DE PAGO:");

        jComboBoxFormPago.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jComboBoxFormPago.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "CONTADO", "CREDITO" }));

        jLabel8.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel8.setText("ESTADO:");

        jComboBoxEstado.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jComboBoxEstado.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "ENTREGADO", "ANULADO", "POR ENTREGAR" }));

        jLabel9.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel9.setText("VENDEDOR:");

        jTextFieldEmpleado.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jTextFieldEmpleado.setText("wcarrasco");
        jTextFieldEmpleado.setEnabled(false);

        jLabelFecha.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabelFecha.setText("00/00/0000");

        javax.swing.GroupLayout jPanelFacturaLayout = new javax.swing.GroupLayout(jPanelFactura);
        jPanelFactura.setLayout(jPanelFacturaLayout);
        jPanelFacturaLayout.setHorizontalGroup(
            jPanelFacturaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelFacturaLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanelFacturaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanelFacturaLayout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addGap(18, 18, 18)
                        .addComponent(jTextFieldNumFactura, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanelFacturaLayout.createSequentialGroup()
                        .addComponent(jLabel9)
                        .addGap(18, 18, 18)
                        .addComponent(jTextFieldEmpleado))
                    .addGroup(jPanelFacturaLayout.createSequentialGroup()
                        .addGroup(jPanelFacturaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel7, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jPanelFacturaLayout.createSequentialGroup()
                                .addGroup(jPanelFacturaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel6)
                                    .addComponent(jLabel8))
                                .addGap(53, 53, 53)))
                        .addGroup(jPanelFacturaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanelFacturaLayout.createSequentialGroup()
                                .addGap(18, 18, 18)
                                .addComponent(jComboBoxEstado, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addGroup(jPanelFacturaLayout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jComboBoxFormPago, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanelFacturaLayout.createSequentialGroup()
                                .addGap(30, 30, 30)
                                .addComponent(jLabelFecha)
                                .addGap(0, 0, Short.MAX_VALUE)))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanelFacturaLayout.setVerticalGroup(
            jPanelFacturaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelFacturaLayout.createSequentialGroup()
                .addGroup(jPanelFacturaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextFieldNumFactura, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanelFacturaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(jLabelFecha))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanelFacturaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBoxFormPago, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanelFacturaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBoxEstado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel8))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanelFacturaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextFieldEmpleado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel9))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanelDetalleFactura.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jScrollPane2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N

        jTable1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jTable1.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, "0", "0"}
            },
            new String [] {
                "CODIGO", "DESCRIPCION", "UND", "P.V.P", "CANTIDAD", "TOTAL"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                true, true, false, false, true, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jTable1.getTableHeader().setResizingAllowed(false);
        jTable1.getTableHeader().setReorderingAllowed(false);
        jScrollPane2.setViewportView(jTable1);

        javax.swing.GroupLayout jPanelDetalleFacturaLayout = new javax.swing.GroupLayout(jPanelDetalleFactura);
        jPanelDetalleFactura.setLayout(jPanelDetalleFacturaLayout);
        jPanelDetalleFacturaLayout.setHorizontalGroup(
            jPanelDetalleFacturaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2)
        );
        jPanelDetalleFacturaLayout.setVerticalGroup(
            jPanelDetalleFacturaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 365, Short.MAX_VALUE)
        );

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jTextFieldSubTotal.setEditable(false);
        jTextFieldSubTotal.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jTextFieldSubTotal.setText("000.000");
        jTextFieldSubTotal.setAutoscrolls(false);

        jTextFieldIva0.setEditable(false);
        jTextFieldIva0.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jTextFieldIva0.setText("000.000");

        jTextFieldIva12.setEditable(false);
        jTextFieldIva12.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jTextFieldIva12.setText("000.000");

        jLabel10.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel10.setText("SUBTOTAL:");

        jLabel11.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel11.setText("IVA 0%:");

        jLabel12.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel12.setText("IVA 12%:");

        jLabelTotal.setFont(new java.awt.Font("Tahoma", 0, 48)); // NOI18N
        jLabelTotal.setText("0000.00");

        jLabel14.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        jLabel14.setText("TOTAL:");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel10)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jTextFieldSubTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel11)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jTextFieldIva0, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel12)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jTextFieldIva12, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel14)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabelTotal)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jLabelTotal)
                .addGap(0, 0, Short.MAX_VALUE))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel14))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(19, 19, 19)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTextFieldSubTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel11)
                            .addComponent(jTextFieldIva0, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel12)
                            .addComponent(jTextFieldIva12, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel10))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanelBotones.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jButtonAceptar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jButtonAceptar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/16px-Crystal_Clear_action_apply.png"))); // NOI18N
        jButtonAceptar.setText("ACEPTAR");
        jButtonAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAceptarActionPerformed(evt);
            }
        });

        jButtonCancelar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jButtonCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/16px-Crystal_Clear_action_button_cancel.png"))); // NOI18N
        jButtonCancelar.setText("CANCELAR");
        jButtonCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanelBotonesLayout = new javax.swing.GroupLayout(jPanelBotones);
        jPanelBotones.setLayout(jPanelBotonesLayout);
        jPanelBotonesLayout.setHorizontalGroup(
            jPanelBotonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelBotonesLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButtonAceptar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 67, Short.MAX_VALUE)
                .addComponent(jButtonCancelar)
                .addContainerGap())
        );
        jPanelBotonesLayout.setVerticalGroup(
            jPanelBotonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jButtonAceptar, javax.swing.GroupLayout.DEFAULT_SIZE, 36, Short.MAX_VALUE)
            .addComponent(jButtonCancelar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanelDetalleFactura, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanelCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 101, Short.MAX_VALUE)
                        .addComponent(jPanelFactura, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(263, 263, 263)
                .addComponent(jPanelBotones, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanelCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 161, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPanelFactura, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanelDetalleFactura, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(11, 11, 11)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanelBotones, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jTextFieldCedulaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldCedulaKeyTyped
        // TODO add your handling code here:
        char t = evt.getKeyChar();
        String[] tupla = new String[10];
        if (!((t >= '0' && t <= '9')) || jTextFieldCedula.getText().length() > 12) {
            evt.setKeyChar('\b');
            if (t == java.awt.event.KeyEvent.VK_ENTER) {// verifico si la tecla presionada es la tecla ENTER
                try {
                    tupla = AD_Clientes.BuscarCI(jTextFieldCedula.getText());//busco el cliente basando en la cedula ingresada
                    if (tupla[0] != null) {//verifico el primer valor de la tupla el cual nunca deberia ser nulo si se encontro el cliente
                        jTextFieldCedula.setText(tupla[1]);
                        jTextFieldNombres.setText(tupla[2] + " " + tupla[3]);
                        jTextAreaDireccion.setText(tupla[4]);
                        jTextFieldTlfno.setText(tupla[5]);
                        jTextFieldCedula.transferFocus();
                    } else {// despliego una pregunta si desea agregar un nuevo cliente
                        int seleccion = JOptionPane.showConfirmDialog(this, "¿NO EXISTE EL CLIENTE, DESEA CREARLO?", "PREGUNTA", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                        if (seleccion == 0) {// creo una instancia para llamar a la ventana cliente                                                       
                            Frm_Clientes obj = new Frm_Clientes();
                            obj.setVisible(true);
                            obj.setLocationRelativeTo(null);


                        }
                    }
                } catch (Exception ex) {
                    Logger.getLogger(Frm_Factura.class
                            .getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }//GEN-LAST:event_jTextFieldCedulaKeyTyped

    private void DatosFormulario(cFactura obj) {
        try {
            String[] tupla = new String[10];

            obj.setNumIDFactura(Integer.parseInt(jTextFieldNumFactura.getText().toString()));

            //busco el ID del cliente con la cedula
            tupla = AD_Clientes.BuscarCI(jTextFieldCedula.getText());
            obj.setNumIDCliente(Integer.parseInt(tupla[0]));

            //busco el ID del Empleado con su usuario
            tupla = AD_Empleado_Users.BuscarUsuario(jTextFieldEmpleado.getText());
            obj.setNumIDEmpleado(Integer.parseInt(tupla[0]));

            //ingreso de los demas parametros
            obj.setTxtFormaPago(jComboBoxFormPago.getSelectedItem().toString());
            obj.setNumSubTotal(Double.parseDouble(jTextFieldSubTotal.getText().toString()));
            obj.setTxtEstado(jComboBoxEstado.getSelectedItem().toString());
            obj.setDateFechaFactura(jLabelFecha.getText().toString());
        } catch (Exception ex) {
            Logger.getLogger(Frm_Factura.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void DatosDetalleFactura() {
        Exception e;
        for (int i = 0; i < (jTable1.getRowCount() - 1); i++) {
            cFactura_Detalle obj = new cFactura_Detalle();
            obj.setNumIDFactura(Integer.parseInt(jTextFieldNumFactura.getText()));
            obj.setNumIDProducto(Integer.parseInt(jTable1.getValueAt(i, 0).toString()));
            obj.setNumCantProducto(Double.parseDouble(jTable1.getValueAt(i, 4).toString()));
            obj.setNumPrecioUnit(Double.parseDouble(jTable1.getValueAt(i, 3).toString()));
            try {
                e = AD_Factura_Detalle.Insertar(obj);
//                if ((e == null) && (i == jTable1.getRowCount())) {
//                    JOptionPane.showMessageDialog(null, "Se ha sido ingresado correctamente", "INSERTAR", JOptionPane.INFORMATION_MESSAGE);
//                } else {
//                    JOptionPane.showMessageDialog(null, "Existe el siguiente error:\n" + e, "ERROR AL INSERTAR", JOptionPane.ERROR_MESSAGE);
//                }
                dispose();
                cConexion.cerrar();
            } catch (Exception ex) {
            }

        }

    }
    private void jButtonAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAceptarActionPerformed
        //codigo para realizar las diferentes tareas Insert,Update,Delete
        Exception e;
        if (CamposNulos() == true) {//verifico que campo se encuentra vacio y advierto
            JOptionPane.showMessageDialog(null, txtnulos, "Campos Vacios", JOptionPane.INFORMATION_MESSAGE);
            txtnulos = "Los Campos Vacios son:\n";
        } else {//Inicio la Insercion
            //para la parte de la factura    
            cFactura obj1 = new cFactura();
            switch (band) {
                case '0':
                    DatosFormulario(obj1);
                    try {
                        e = AD_Factura.Insertar(obj1);
                        //para el detalle de la factura            
                        DatosDetalleFactura();
                        if (e == null) {
                            JOptionPane.showMessageDialog(null, "Se ha sido ingresado correctamente", "INSERTAR", JOptionPane.INFORMATION_MESSAGE);
                        } else {
                            JOptionPane.showMessageDialog(null, "Existe el siguiente error:\n" + e, "ERROR AL INSERTAR", JOptionPane.ERROR_MESSAGE);
                        }
                        dispose();
                        cConexion.cerrar();
                    } catch (Exception ex) {
                        Logger.getLogger(Frm_Clientes.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    break;
                case '1':
                    DatosFormulario(obj1);
                    try {
                        e = AD_Factura.Actualizar(obj1);                        
                        if (e == null) {
                            JOptionPane.showMessageDialog(null, "Se ha sido actualizado correctamente", "ACTUALIZAR", JOptionPane.INFORMATION_MESSAGE);
                        } else {
                            JOptionPane.showMessageDialog(null, "Existe el siguiente error:\n" + e, "ERROR AL ACTUALIZAR", JOptionPane.ERROR_MESSAGE);
                        }
                        dispose();
                        cConexion.cerrar();
                    } catch (Exception ex) {
                        Logger.getLogger(Frm_Clientes.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    break;

            }
        }//Terminamos con la Insercion
//            else {//Inicio de Actualizacion
//                if (jRadioButtonUpdate.isSelected() == true) {
//                    cCategoria obj1 = new cCategoria();
//                    DatosFormulario(obj1);
//                    try {
//
//                        e = AD_Categoria.Actualizar(obj1);
//                        if (e == null) {
//                            JOptionPane.showMessageDialog(null, "Los datos se han actualizado correctamente", "MODIFICAR", JOptionPane.INFORMATION_MESSAGE);
//                        } else {
//                            JOptionPane.showMessageDialog(null, "Existe el siguiente error:\n" + e, "ERROR AL MODIFICAR", JOptionPane.ERROR_MESSAGE);
//                        }
//                        dispose();
//                        cConexion.cerrar();
//                    } catch (Exception ex) {
//                        Logger.getLogger(Frm_Clientes.class.getName()).log(Level.SEVERE, null, ex);
//                    }
//                }//terminanos con la Actualizacion
//                else {//Iniciamos la Eliminacion
//                    try {
//
//                        e = AD_Categoria.Eliminar(jTextFieldNomCategoria.getText());
//                        if (e == null) {
//                            JOptionPane.showMessageDialog(null, "Los datos se han Eliminado correctamente", "ELIMINAR", JOptionPane.INFORMATION_MESSAGE);
//                        } else {
//                            JOptionPane.showMessageDialog(null, "Existe el siguiente error:\n" + e, "ERROR AL ELIMINAR", JOptionPane.ERROR_MESSAGE);
//                        }
//                        dispose();
//                        cConexion.cerrar();
//                    } catch (Exception ex) {
//                        Logger.getLogger(Frm_Clientes.class.getName()).log(Level.SEVERE, null, ex);
//                    }
//                }//Terminamos la Eliminacion
//            }
//        }        
    }//GEN-LAST:event_jButtonAceptarActionPerformed

    private void jButtonCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelarActionPerformed
        try {
            // TODO add your handling code here:
            dispose();
            cConexion.cerrar();


        } catch (Exception ex) {
            Logger.getLogger(Frm_Clientes.class
                    .getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButtonCancelarActionPerformed

    private void jTextFieldNumFacturaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldNumFacturaKeyTyped
        // TODO add your handling code here:
        char t = evt.getKeyChar();
        if (!((t >= '0' && t <= '9')) || jTextFieldNumFactura.getText().length() > 7) {
            evt.setKeyChar('\b');
            // verifico si la tecla presionada es la tecla ENTER
            if (t == java.awt.event.KeyEvent.VK_ENTER) {
                try {
                    if (AD_Factura.GetNumFactura(Integer.parseInt(jTextFieldNumFactura.getText().toString())) == 0) {
                        jTable1.setValueAt("", 0, 0);
                        jTable1.changeSelection(0, 0, false, false);
                        jTable1.editCellAt(0, 0);
                        jTable1.requestFocus();
                    } else {
                        JOptionPane.showMessageDialog(null, "EL NUMERO DE FACTURA YA EXISTE", "ERROR", JOptionPane.ERROR_MESSAGE);
                    }
                } catch (Exception ex) {
                    Logger.getLogger(Frm_Factura.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }//GEN-LAST:event_jTextFieldNumFacturaKeyTyped

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;


                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Frm_Factura.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Frm_Factura.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Frm_Factura.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Frm_Factura.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Frm_Factura("", 0).setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonAceptar;
    private javax.swing.JButton jButtonCancelar;
    private javax.swing.JComboBox jComboBoxEstado;
    private javax.swing.JComboBox jComboBoxFormPago;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JLabel jLabelFecha;
    private javax.swing.JLabel jLabelTotal;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanelBotones;
    private javax.swing.JPanel jPanelCliente;
    private javax.swing.JPanel jPanelDetalleFactura;
    private javax.swing.JPanel jPanelFactura;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextArea jTextAreaDireccion;
    private javax.swing.JTextField jTextFieldCedula;
    private javax.swing.JTextField jTextFieldEmpleado;
    private javax.swing.JTextField jTextFieldIva0;
    private javax.swing.JTextField jTextFieldIva12;
    private javax.swing.JTextField jTextFieldNombres;
    private javax.swing.JTextField jTextFieldNumFactura;
    private javax.swing.JTextField jTextFieldSubTotal;
    private javax.swing.JTextField jTextFieldTlfno;
    // End of variables declaration//GEN-END:variables
}
